import { FC, useState } from "react";
import {
  Button,
  DatePicker,
  Form,
  Input,
  Message,
  Modal,
  Select,
  Space,
} from "@arco-design/web-react";
import { css } from "@emotion/css";
import { Role, Sex, SystemUserDataRow } from "../../api/types/system-user.ts";
import { useAPI } from "../../hooks/useAPI.ts";
import Password from "@arco-design/web-react/es/Input/password";
import { useMutation, useQuery } from "react-query";
import { SearchBuildingParams } from "../../api/types/building.tsx";
import { encrypt } from "../../utils/encrypt.ts";
import { UpdatePasswordModal } from "../UpdatePasswordModal";
import { IconClose, IconCheck, IconLock } from "@arco-design/web-react/icon";

export interface BuildingAdminModalProps {
  visible?: boolean;
  onClose?: () => void;
  onSuccess?: () => void;
  title?: string;
  userId?: number;
  isEdit?: boolean;
  isEditPassword?: boolean;
  isBuildingAdmin?: boolean;
  userData?: SystemUserDataRow;
}

export const BuildingAdminModal: FC<BuildingAdminModalProps> = ({
  visible,
  onClose,
  onSuccess,
  title,
  userId,
  isEdit = false,
  isEditPassword = false,
  isBuildingAdmin,
  userData,
}) => {
  const api = useAPI();
  const [formRef] = Form.useForm();
  const [currentBuildingId, setCurrentBuildingId] = useState<number | null>(
    userData?.buildingId ?? null,
  );
  if (userData?.roles[0]?.roleId) {
    userData.roleIds = userData.roles[0].roleId;
  }
  const [isOpenUpdatePasswordModal, setIsOpenUpdatePasswordModal] =
    useState(false);
  const submitForm = useMutation(async () => {
    try {
      const values = await formRef.validate();
      values.roleIds = [values.roleIds];
      values.password = encrypt(values.password);
      if (isEdit) {
        values.userId = userId ? userId : userData?.userId;
        values.buildingId = currentBuildingId ?? values.buildingId;
        await api.updateSystemUser(userData);
      } else {
        values.userName = values.phonenumber;
        await api.createSystemUser(values);
      }
      onSuccess?.();
      formRef.resetFields();
      Message.success("操作成功");
    } catch (error) {
      if (error instanceof Error) {
        Message.error(error.message);
      } else {
        Message.error("操作失败，请稍后重试");
      }
    }
  });
  const buildingListParams: SearchBuildingParams = {
    pageNum: 1,
    pageSize: 1000,
  };
  const { data: buildingList } = useQuery(
    ["query-building-list", buildingListParams],
    async () => {
      const response = await api.getBuildingList(buildingListParams);
      if (!response.data.data) {
        throw new Error("No Data");
      }
      return response.data.data;
    },
  );

  if (userData) {
    userData.roleIds = userData?.roles?.[0]?.roleId;
  }

  return (
    <Modal
      visible={visible}
      onCancel={() => {
        formRef.resetFields();
        setCurrentBuildingId(null);
        onClose?.();
      }}
      footer={null}
      title={title}
      unmountOnExit
      mountOnEnter
    >
      <UpdatePasswordModal
        visible={isOpenUpdatePasswordModal}
        defaultData={userData}
        onClose={() => {
          setIsOpenUpdatePasswordModal(false);
        }}
        onSuccess={() => {
          setIsOpenUpdatePasswordModal(false);
        }}
      />

      <Form form={formRef} initialValues={userData!}>
        <Form.Item label="USERNAME" field="userName" disabled hidden>
          <Input />
        </Form.Item>

        <Form.Item
          label="姓名"
          field="nickName"
          rules={[
            {
              required: true,
              message: "姓名不得为空",
            },
          ]}
        >
          <Input placeholder="请输入姓名" />
        </Form.Item>
        <Form.Item
          label="性别"
          field="sex"
          rules={[
            {
              required: true,
              message: "请选择性别",
            },
          ]}
        >
          <Select placeholder="请选择性别">
            <Select.Option value={Sex.Man}>男</Select.Option>
            <Select.Option value={Sex.Woman}>女</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="生日"
          field="birth"
          rules={[
            {
              required: true,
              message: "请选择生日",
            },
          ]}
        >
          <DatePicker placeholder="请选择生日" style={{ width: "380px" }} />
        </Form.Item>

        {!isEdit && (
          <Form.Item
            label="密码"
            field="password"
            rules={[
              {
                required: true,
                message: "密码不得为空",
              },
              {
                minLength: 6,
                validator(value, cb) {
                  const regex = /^[A-Za-z0-9]{6,}$/;
                  if (regex.test(value)) {
                    cb(null);
                  } else {
                    cb("密码至少6位（区分大小写），不包括特殊字符");
                  }
                },
              },
              {
                maxLength: 16,
                message: "密码最多16位",
              },
            ]}
          >
            <Password placeholder="请输入密码" />
          </Form.Item>
        )}

        {!isBuildingAdmin && (
          <Form.Item
            label="角色"
            field="roleIds"
            rules={[
              {
                required: true,
                message: "角色不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择角色"
              value={userData?.roles?.[0]?.roleId}
            >
              <Select.Option value={Role.CommunityLeader}>
                医院办公室
              </Select.Option>
              <Select.Option value={Role.Control}>总值班</Select.Option>
              <Select.Option value={Role.BuildingAdmin}>护理部</Select.Option>
              <Select.Option value={Role.ElderUser}>长辈</Select.Option>
            </Select>
          </Form.Item>
        )}
        {isBuildingAdmin && (
          <Form.Item
            label="角色"
            field="roleIds"
            rules={[
              {
                required: true,
                message: "角色不得为空",
              },
            ]}
          >
            <Select
              placeholder="请选择角色"
              value={userData?.roles?.[0]?.roleId}
            >
              <Select.Option value={Role.BuildingAdmin}>楼管</Select.Option>
            </Select>
          </Form.Item>
        )}
        {userData?.roles?.[0]?.roleId === Role.BuildingAdmin && (
          <Form.Item label="管理位置">
            <Select
              onChange={(v) => setCurrentBuildingId(v)}
              defaultValue={userData?.buildingName}
              allowClear
              placeholder="请选择管理位置"
              options={buildingList?.rows
                // .filter((v) => v.managers.length === 0)
                .map((item) => ({
                  label: item.name,
                  value: item.id,
                }))}
              showSearch
              filterOption={(input, option) =>
                option?.props.children
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
            />
          </Form.Item>
        )}

        <Form.Item
          label="手机号"
          field="phonenumber"
          rules={[
            {
              required: true,
              validator(value, cb) {
                const phoneNumberRegex = /^1[3-9]\d{9}$/;
                if (!phoneNumberRegex.test(value)) {
                  return cb("请输入正确格式的电话号码");
                }
                return cb(null);
              },
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item label="家属名" field="contactName">
          <Input placeholder="请输入家属姓名" />
        </Form.Item>

        <Form.Item
          label="家属电话"
          field="contactPhonenumber"
          rules={[
            {
              validator(value, cb) {
                const phoneNumberRegex = /^1[3-9]\d{9}$/;
                if (!value) {
                  return cb(null);
                }

                const phoneNumbers = value
                  .split(",")
                  .map((num: any) => num.trim());

                if (phoneNumbers.length > 3) {
                  return cb("最多只能输入三个电话号码");
                }

                for (const num of phoneNumbers) {
                  if (!phoneNumberRegex.test(num)) {
                    return cb(
                      "请输入正确格式的电话号码，每个号码用逗号分隔，最多三个。",
                    );
                  }
                }

                return cb(null);
              },
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item label="家庭住址" field="address">
          <Input.TextArea placeholder="请输入家庭住址" />
        </Form.Item>

        <Space
          className={css`
            margin-top: 16px;
            padding: 12px 0;
            display: flex;
            justify-content: end;
          `}
        >
          {isEdit && isEditPassword && (
            <Button
              type="secondary"
              htmlType="submit"
              loading={submitForm.isLoading}
              onClick={() => setIsOpenUpdatePasswordModal(true)}
              icon={<IconLock />}
            >
              修改密码
            </Button>
          )}

          <Button
            type="primary"
            htmlType="submit"
            loading={submitForm.isLoading}
            onClick={() => submitForm.mutateAsync()}
            icon={<IconCheck />}
          >
            完成
          </Button>
          <Button
            type="outline"
            htmlType="button"
            onClick={() => {
              formRef.resetFields();
              setCurrentBuildingId(null);
              onClose?.();
            }}
            icon={<IconClose />}
          >
            取消
          </Button>
        </Space>
      </Form>
    </Modal>
  );
};
